document.addEventListener('DOMContentLoaded', function() {
    // 星级评分处理
    const starContainers = document.querySelectorAll('.star-rating');
    
    starContainers.forEach(container => {
        const stars = container.querySelectorAll('.star');
        const ratingValue = container.querySelector('.rating-value');
        let selectedRating = 0;
        
        // 鼠标悬停效果
        stars.forEach(star => {
            star.addEventListener('mouseover', function() {
                const rating = this.dataset.rating;
                updateStars(stars, rating);
            });
            
            // 点击选择评分
            star.addEventListener('click', function() {
                selectedRating = this.dataset.rating;
                updateStars(stars, selectedRating);
                ratingValue.textContent = selectedRating + ' 分';
            });
        });
        
        // 鼠标移出时恢复已选择的评分
        container.addEventListener('mouseleave', function() {
            updateStars(stars, selectedRating);
        });
    });

    // 文字计数
    const textarea = document.querySelector('textarea');
    const wordCount = document.querySelector('.word-count');
    
    textarea.addEventListener('input', function() {
        const length = this.value.length;
        wordCount.textContent = `${length}/500`;
    });

    // 标签切换
    const tabs = document.querySelectorAll('.tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            tabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
        });
    });

    // 处理表单提交
    const submitBtn = document.querySelector('.submit-btn');
    submitBtn.addEventListener('click', function(e) {
        e.preventDefault();
        handleSubmitFeedback();
    });
});

// 更新星星显示状态
function updateStars(stars, rating) {
    stars.forEach(star => {
        if (star.dataset.rating <= rating) {
            star.innerHTML = '★';
            star.classList.add('active');
        } else {
            star.innerHTML = '☆';
            star.classList.remove('active');
        }
    });
}

// 显示反馈成功弹窗
function showFeedbackModal() {
    const modal = document.createElement('div');
    modal.className = 'feedback-modal';
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-icon">✓</div>
            <h3>反馈提交成功</h3>
            <p>我们已收到您的反馈，感谢您的评价！</p>
            <button class="modal-close">确定</button>
        </div>
    `;

    document.body.appendChild(modal);

    // 添加淡入效果
    setTimeout(() => modal.classList.add('show'), 10);

    // 点击确定按钮关闭弹窗
    const closeBtn = modal.querySelector('.modal-close');
    closeBtn.addEventListener('click', () => {
        modal.classList.remove('show');
        setTimeout(() => modal.remove(), 300);
    });
}

// 重置所有反馈内容
function resetFeedback() {
    // 重置星级评分
    const starContainers = document.querySelectorAll('.star-rating');
    starContainers.forEach(container => {
        const stars = container.querySelectorAll('.star');
        const ratingValue = container.querySelector('.rating-value');
        stars.forEach(star => {
            star.innerHTML = '☆';
            star.classList.remove('active');
        });
        ratingValue.textContent = '0 分';
    });

    // 清空文本框
    const textarea = document.querySelector('textarea');
    if (textarea) {
        textarea.value = '';
        const wordCount = document.querySelector('.word-count');
        if (wordCount) {
            wordCount.textContent = '0/500';
        }
    }

    // 清空联系方式表单
    const inputs = document.querySelectorAll('.form-group input');
    inputs.forEach(input => input.value = '');
}

// 处理表单提交
async function handleSubmitFeedback() {
    // 检查登录状态
    const token = localStorage.getItem('token');
    if (!token) {
        showErrorModal('需要登录', '请完成登录再对该系统进行反馈');
        setTimeout(() => {
            window.location.href = 'auth.html#login';
        }, 2000);
        return;
    }

    let isValid = true;
    let errorMessages = [];

    // 获取评分值
    const overallSatisfaction = document.querySelector('.rating-section:nth-child(1) .rating-value').textContent.split(' ')[0];
    const ratingAccuracy = document.querySelector('.rating-section:nth-child(2) .rating-value').textContent.split(' ')[0];
    const userExperience = document.querySelector('.rating-section:nth-child(3) .rating-value').textContent.split(' ')[0];

    // 检查评分
    if (overallSatisfaction === '0' || ratingAccuracy === '0' || userExperience === '0') {
        isValid = false;
        errorMessages.push('请完成所有评分项');
    }

    // 检查详细反馈
    const feedback = document.querySelector('textarea').value.trim();
    if (!feedback) {
        isValid = false;
        errorMessages.push('请填写详细反馈内容');
    }

    // 获取联系方式
    const name = document.getElementById('name').value.trim();
    const phone = document.getElementById('phone').value.trim();
    const email = document.getElementById('email').value.trim();

    // 如果有错误，显示提示信息
    if (!isValid) {
        alert('请完善以下信息：\n' + errorMessages.join('\n'));
        return;
    }

    try {
        const response = await fetch(`${API_BASE_URL}/system/feedback`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
                overall_satisfaction: parseInt(overallSatisfaction),
                rating_accuracy: parseInt(ratingAccuracy),
                user_experience: parseInt(userExperience),
                feedback: feedback,
                name: name,
                phone: phone,
                email: email
            })
        });

        const data = await response.json();

        if (data.code === 200) {
            showFeedbackModal();
            resetFeedback();
        } else if (data.code === 401 || data.message.includes('令牌')) {
            // 处理令牌相关错误
            showErrorModal('需要登录', '请完成登录再对该系统进行反馈');
            setTimeout(() => {
                localStorage.removeItem('token'); // 清除无效的token
                window.location.href = 'auth.html#login';
            }, 2000);
        } else {
            throw new Error(data.message || '提交反馈失败');
        }
    } catch (error) {
        if (error.message.includes('令牌')) {
            showErrorModal('需要登录', '请完成登录再对该系统进行反馈');
            setTimeout(() => {
                localStorage.removeItem('token'); // 清除无效的token
                window.location.href = 'auth.html#login';
            }, 2000);
        } else {
            showErrorModal('提交反馈失败', error.message);
        }
    }
}

// 显示错误弹窗
function showErrorModal(title, message) {
    const modal = document.createElement('div');
    modal.className = 'feedback-modal';
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-icon failure">✕</div>
            <h3>${title}</h3>
            <p>${message}</p>
            <button class="modal-close">确定</button>
        </div>
    `;

    document.body.appendChild(modal);
    setTimeout(() => modal.classList.add('show'), 10);

    const closeBtn = modal.querySelector('.modal-close');
    closeBtn.addEventListener('click', () => {
        modal.classList.remove('show');
        setTimeout(() => modal.remove(), 300);
    });
}